package asset
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.geom.Point;
	import flash.utils.describeType;
	
	import iso.IsoSprite;
	
	public class AssetBase extends IsoSprite
	{
		private var _asset:DisplayObject;
		private var _sourceAsset:*;
		private var _point:Point;
		
		public function AssetBase(sourceAsset:*, isLoadAsset:Boolean=true, point:Point=null)
		{
			_sourceAsset=sourceAsset;
			_point=point;
			
			if(_sourceAsset && isLoadAsset) loadAsset();
		}
		
		/**
		 *加载物件 
		 */
		public function loadAsset():void
		{
			clearAsset();
			
			var classType:String=String(describeType(_sourceAsset).@base);
			switch(classType)
			{
				case "flash.display::BitmapData":
					addAssetItem(new Bitmap(_sourceAsset as BitmapData));
					break;
				case "flash.display::MovieClip":
					addAssetItem(_sourceAsset as MovieClip);
					break;
			}
		}
		
		/**
		 * 执行增加
		 * @param dis 物件对象
		 */		
		private function addAssetItem(dis:DisplayObject):void
		{
			if(!_point)
			{
				_point=new Point();
				_point.x=-dis.width/2;
				_point.y=-dis.height;
			}
			
			dis.x=_point.x;
			dis.y=_point.y;
			asset=dis;
		}
		
		public function get asset():DisplayObject
		{
			return _asset;
		}
		
		public function set asset(value:DisplayObject):void
		{
			_sourceAsset=null;
			clearAsset();
			_asset = value;
			addChild(_asset);
		}
		
		private function clearAsset():void
		{
			if(_asset as Bitmap)
			{
				var bmp:Bitmap=_asset as Bitmap;
				if(bmp)
				{
					if(bmp.parent) bmp.parent.removeChild(bmp);
					bmp.bitmapData.dispose();
					bmp.bitmapData=null;
				}
				bmp=null;
			}
			if(_asset && _asset.parent) _asset.parent.removeChild(_asset);
			_asset=null;
		}
		
		override public function dispose():void
		{
			super.dispose();
			if(_sourceAsset is BitmapData)
			{
				var bd:BitmapData=_sourceAsset as BitmapData;
				if(bd) bd.dispose();
				bd=null;
			}
			_sourceAsset=null;
			
			clearAsset();
			if(parent) parent.removeChild(this);
		}

		/**
		 *物件对象对象(非资源基)的坐标
		 */		
		public function get point():Point
		{
			return _point;
		}

		/**
		 *物件对象对象(非资源基)的坐标 
		 */	
		public function set point(value:Point):void
		{
			_point = value;
		}

		public function get sourceAsset():*
		{
			return _sourceAsset;
		}

		public function set sourceAsset(value:*):void
		{
			if(_sourceAsset is BitmapData)
			{
				var bd:BitmapData=_sourceAsset as BitmapData;
				if(bd) bd.dispose();
				bd=null;
			}
			_sourceAsset=null;
			
			_sourceAsset = value;
		}

	}
}